<template>
  <el-form ref="form" :model="form" label-width="80px" :rules="rules">
            <!-- 执行单位部门 -->
            <el-row>
              <el-col :span="8">
                <el-form-item label="客户名称">
                  <el-input v-model="form.partner_id" placeholder="客户名称待分配" :disabled="isdisabled"></el-input>
                </el-form-item>
              </el-col>
                <!-- 公司 -->
            <el-col :span="8">
                <el-form-item label="执行公司" prop="gsid">
                <el-select v-model="form.gsid" placeholder="公司" style="width:100%;">
                <el-option :label="v['name']" :value="v['id']" v-for="(v,i) in companys" :key="i"></el-option>
                </el-select>
            </el-form-item>
            </el-col>
            <!-- 部门 -->
            <el-col :span="8">
                <el-form-item label="执行部门">
                  <el-input v-model="form.deptName" placeholder="部门" style="width:100%;" disabled></el-input>
                </el-form-item>
            </el-col>
            </el-row>

          <el-row>
            <el-col :span="8">
              <el-form-item label='项目名称' prop="name">
                <el-input v-model="form.name" placeholder="项目名称"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="项目负责">
                <el-input v-model="form.leader" placeholder="项目负责" disabled></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="项目电话" prop="leader_mobile">
                <el-input v-model="form.leader_mobile" placeholder="项目电话" maxlength="11"></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="8">
              <el-form-item label="项目编号">
                <el-input v-model="form.batch_id" placeholder="项目编号" disabled></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="客户对接" prop="customer">
                <el-input v-model="form.customer" placeholder="客户对接"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="客户电话" prop="customer_mobile">
                <el-input v-model="form.customer_mobile" placeholder="客户电话" maxlength="11"></el-input>
              </el-form-item>
            </el-col>
          </el-row>

    <!--    销售经理,销售电话-->
        <el-row>
          <el-col :span="8">
            <!--项目城市-->
            <el-form-item label="项目城市" prop="city">
              <el-input v-model="form.city" placeholder="项目城市" ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="销售经理" prop="seller">
              <el-input v-model="form.seller" placeholder="销售经理"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="销售电话" prop="seller_mobile">
              <el-input v-model="form.seller_mobile" placeholder="销售电话" maxlength="11"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
          <!--客户报价,项目成本-->
          <el-row>
            <el-col :span="8">
              <!-- 币种选择 流程选择-->
              <el-form-item label="项目币种" prop="currency">
                <el-select v-model="form.currency" placeholder="项目币种" style="width:100%;" @change="changeMoneyCurrency">
                  <el-option v-for="(v,i) in currencys" :key="i" :label="v.currency" :value="v.currency" ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="客户报价" prop="offer">
                <el-input
                  v-model="form.offer"
                  placeholder="客户报价"
                  @blur="changeOffer"
                  @focus="resetInput('offer')"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="项目成本" prop="cost">
                <el-input v-model="form.cost" placeholder="项目成本" @blur="changeCost" @focus="resetInput('cost')"></el-input>
              </el-form-item>
            </el-col>
          </el-row>


            <!-- 开始时间 结束时间 -->
            <el-row>
              <!-- 开始时间 -->
              <el-col :span="8">
                <el-form-item label="立项时间" prop="created_at">
                  <el-date-picker
                    type="date"
                    placeholder="选择日期"
                    v-model="form.created_at"
                    style="width: 100%;" value-format="yyyy-MM-dd"
                    :picker-options="pickerOptions"
                  >

                  </el-date-picker>
                </el-form-item>
              </el-col>
                <!-- 开始时间 -->
            <el-col :span="8">
                <el-form-item label="开始时间" prop="start">
                <el-date-picker
                  type="date"
                  placeholder="选择日期"
                  v-model="form.start"
                  style="width: 100%;" value-format="yyyy-MM-dd"
                  :picker-options="pickerOptionsStart"
                  @focus="checkCreatedAt"
                  :readonly="createdRead"
                >
                </el-date-picker>
            </el-form-item>
            </el-col>
            <!-- 结束时间 -->
            <el-col :span="8">
                <el-form-item label="结束时间" prop="stop">
                <el-date-picker type="date" placeholder="选择日期" v-model="form.stop" style="width: 100%;" value-format="yyyy-MM-dd" :picker-options="pickerOptionsEnd" @focus="checkStartAt" :readonly="startRead"></el-date-picker>
            </el-form-item>
            </el-col>
            </el-row>

        <!--备注信息-->
            <el-form-item label="备注信息" prop="desc">
              <el-input
                type="textarea"
                v-model="form.desc"
                maxlength="1500"
                show-word-limit
              ></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="onSubmit('form',0)">提交</el-button>
                <el-button type="primary" @click="onSubmit('form',1)">保存</el-button>
                <el-button @click="resetForm('form')">取消</el-button>
            </el-form-item>
            </el-form>
</template>

<script>
import {getCommonSelect,getCompanyDept} from '@/apilist/public'
import {rules} from '@/rules/rules'
import {addNewWork} from '@/apilist/Project'
import {mapState} from "vuex";

export default {
name:"project_lx",
    data(){
        return {
        form: {
          name: '',
          gsid: '',
          start: '',
          stop: '',
          delivery: false,
          type: [],
          resource: '',
          desc: '',
          deptid:'',
          leader: this.leaderComputed,//负责人
          leader_mobile:'',//负责人电话
          currency:'CNY',//币种
          offer:this.fun.fmoney("0.00"),
          cost:this.fun.fmoney("0.00"),
          city:'',
          seller:'',//销售经理
          seller_mobile:'',//销售经理电话
          customer:'',//客户负责人
          customer_mobile: '',//客户电话
          work_id: 1,//流程ID
          partner_id:'',//合作商
          is_save: '',
          batch_id: '',
          xmid: 0,
          deptName: '',
          created_at: '',
        },
        createdRead: true,
        startRead: true,
          btnFlag:true,
        isdisabled:true,
        depts:[''],
        companys:[],
        currencys:[],
        rules:rules,
        work_list: [],
        deptName: '',
          //时间限制，符合日期先后顺序的实际情况
          pickerOptionsStart: {
            disabledDate: time => {
              if (this.form.created_at) {
                  return  time.getTime() < new Date(this.form.created_at).getTime()  /*开始日期要在选择的结束日期之前*/
              }
              // return time.getTime() < Date.now() - 8.64e7; /*今天及以后*/
              return time.getTime() > Date.now() - 8.64e6; /*今天及之前，注意数字不一样*/
            }
          },
          pickerOptionsEnd: {
            disabledDate: time => {
              if (this.form.start) {
                 return  time.getTime() < new Date(this.form.start).getTime()  /*开始日期要在选择的结束日期之前*/;
              }
              return time.getTime() > Date.now() - 8.64e6; /*今天及之前*/
            }
          }


        }
    },
  computed: {
    ...mapState("Common",["pickerOptions"]),
    leaderComputed() {
      let userinfo =sessionStorage.getItem("userinfo")
      return userinfo?JSON.parse(userinfo).username:''
    }
  },

    methods: {
      // 提交表单
      async onSubmit(formName, is_save) {
        if(!this.btnFlag) return
         this.btnFlag = false;
        try {
          // 1. 将 validate 改为 Promise 形式，以便用 await 捕获错误
          const valid = await new Promise((resolve, reject) => {
            this.$refs[formName].validate((valid, obj) => {
              if (!valid) {
                const firstKey = Object.keys(obj)[0] || ''
                reject(new Error(obj[firstKey][0]['message'] || '校验失败'))
              } else {
                resolve(true)
              }
            })
          })

          // 2. 正确使用防抖：先创建防抖函数再调用
          const debouncedSubmit = this.addProjectLx
          await debouncedSubmit(is_save) // ✅ 传递参数并等待执行
          this.btnFlag = true;

        } catch (error) {
          this.btnFlag = true;
           Promise.reject(error)
          return false
        }
      },

      //添加立项
      async addProjectLx(is_save){
        try {
          this.form.is_save = is_save
          let params = this.form
          const res = await addNewWork(params);
          if (res.state != 'ok') throw new Error(res.message)
          await this.$success(res.msg)
          this.form.xmid = res.data.xmid
          this.$router.push({
            path: "/project_list",
            query: {
              status: is_save ? 0 : 1,
              tab: 0,
            },
          })
        }catch (e){
          throw e;
        }
      },

      getDepts(gsid){

          return true;
          this.depts = [];
          getCompanyDept({'gsid':gsid}).then(res => {
              this.depts = res.data.list.dept_list
              this.form.deptid = ''

              this.work_list = res.data.list.work_list
              this.form.work_id = ''

              this.$forceUpdate()
          })
      },
      //报价,成本修改
      changeOffer(){
        let that = this;
        that.form.offer = that.fun.fmoney(that.form.offer);
      },
      changeCost(){
        let that = this;
        that.form.cost = that.fun.fmoney(that.form.cost);
      },
      resetForm(formName){

        this.$refs[formName].resetFields();
      },
        changeMoneyCurrency(){
          let that = this;

            console.log(that.form.offer)

            that.form.offer = that.fun.fmoney(that.form.offer);

            that.form.cost = that.fun.fmoney(that.form.cost);
        },

      resetInput(key){
        if(this.form[key] == '0.00' || this.form[key]== this.form.currency + ' ' + '0.00'){
          this.form[key] = '';
        }
      },
      checkCreatedAt(){
        if(!this.form.created_at){
          this.$message.error('请选择立项时间');
          return false;
        }
        this.createdRead = false;
      },
      checkStartAt(){
        if(!this.form.start) {
          this.$message.error('请选择开始时间');
          return false;
        }
        this.startRead = false;
      },




    },


    mounted(){

      let userinfo = this.fun.getUserInfo()
      console.log(userinfo)
      this.form.leader = userinfo.username
      this.form.deptid = parseInt(userinfo.dept_id)
      this.form.deptName = userinfo.dept_name


      getCommonSelect({
        type:['company','currency'],
        deptid: this.form.deptid
      }).then(res=>{
            this.companys = res.data.company;
            this.currencys = res.data.currency;
        });



    },
}
</script>

<style>

</style>
